//子路由
let express = require("express"); //绝对路径
const { ObjectId } = require("mongodb");
//创建路由对象
let Router = express.Router(); //Router==app
let mongo = require("../../db/mongo");
let { create, verify } = require("./token"); //引入jsonwebtoken插件
let upload = require("./multer");
let config = require("../../config.json");

/*
  用户管理：restful接口规范
    * 验证用户名是否存在 ：get
    * 注册 : post 
    * 登录 : get 生成token 下一次:验证token
    * 删除用户 : delete
    * 查询用户列表 :get
    * 修改用户信息 :put
*/

//1.验证用户名是否存在
//访问该接口: /user/checkname
Router.get("/checkname", async (req, res) => {
  let result = {};
  // console.log(req.query);
  try {
    // let data = await mongo.lowfind("users", req.query);//方法一
    let data = await mongo.find("users", { findquery: req.query }); //方法一
    // console.log(data);

    if (data.code) {
      //验证有:不能注册
      result = {
        code: 0,
        message: "不能注册,用户已存在",
      };
    } else {
      result = {
        code: 1,
        message: "允许注册",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  res.send(result); //响应数据给前端
});

//2.注册
Router.post("/reg", async (req, res) => {
  //post请求 body
  // console.log(req.body);
  let arr = [];
  let result = {};
  arr.push(req.body);
  try {
    let data = await mongo.create("users", arr); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    if (data.code) {
      result = {
        code: 1,
        message: "注册成功",
      };
    } else {
      result = {
        code: 0,
        message: "注册失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }

  res.send(result); //响应数据给前端
});

//3.登录
Router.get("/login", async (req, res) => {
  let result = {};
  // console.log(req.query);
  try {
    let data = await mongo.find("users", { findquery: req.query }); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    console.log(data);
    if (data.code) {
      //登录成功
      //生成token
      let token = create(req.query.password);
      result = {
        code: 1,
        message: "登录成功",
        token,
      };
    } else {
      result = {
        code: 0,
        message: "账号或密码错误",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
});

//4.验证token:用在前端的路由守卫里面==路由拦截
Router.get("/verify", (req, res) => {
  let { token } = req.query; //前端传过来的token
  let result = {};
  let data = verify(token);
  if (data) {
    //校验通过
    result = {
      code: 1,
      message: "token校验通过",
    };
  } else {
    //校验失败
    result = {
      code: 0,
      message: "token校验不通过",
    };
  }
  res.send(result); //校验响应给前端
});

//5.删除用户
Router.delete("/del/:_id", async (req, res) => {
  // console.log(req.params);
  let _id = ObjectId(req.params._id);
  // console.log(_id);
  let query = {
    _id,
  }; //{_id:ObjectId(5f51a143db619cff3c548934)}
  let result = {};
  try {
    let data = await mongo.remove("users", query); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    if (data.code) {
      //登录成功
      //生成token
      result = {
        code: 1,
        message: "删除成功",
      };
    } else {
      result = {
        code: 0,
        message: "删除失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

//6.查询用户列表
Router.get("/list", async (req, res) => {
  //用户传：page:1 页码；pagesize:10;过来
  console.log(req.query);
  let query = {
    page: req.query.page - 0,
    pagesize: req.query.pagesize * 1,
  };
  let result = {};
  try {
    let data = await mongo.find("users", query); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    console.log(data);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

//7.修改用户信息
Router.put("/edit/:id", async (req, res) => {
  //req.params动态路由用来接收id；req.body 接收要修改的新数据
  // console.log(req.params, 111);
  // console.log(req.body, 222);
  let query = {
    _id: ObjectId(req.params.id),
  };
  // console.log(query, 111);
  // console.log(req.body, 222);
  let result = {};
  try {
    let data = await mongo.update("users", query, req.body); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    // console.log(data);
    result = data;
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

// let obj = {
//   name: 1,
//   age: 2,
//   adr: 3,
// };

// let obj2 = obj; //引用写法：浅拷贝

// //深度拷贝
// let str = JSON.stringify(obj);
// let obj2 = JSON.parse(str);

// let obj2 = {
//   name : obj.name,
//   age : obj.age,
//   adr : obj.adr
// }

// //扩展运算符
// let obj2 = {
//   ...obj
// }

//8.上传头像：更新用户数据
Router.post("/upload/:id", upload.single("avatar"), async (req, res) => {
  let url = "http://localhost:" + config.PORT + "/";
  url = url + req.file.destination + req.file.filename; //路径已经拼接好，准备存入到数据库里面
  let query = {
    _id: ObjectId(req.params.id),
  };
  console.log(query, 111);
  let newdata = {
    headphoto: url,
    ...req.body,
  };
  console.log(newdata, 222);
  //更新数据库
  let result = {};
  try {
    let data = await mongo.update("users", query, newdata);
    if (data.code) {
      //上传头像成功
      result = {
        code: 1,
        message: "上传头像成功",
      };
    } else {
      //上传头像失败
      result = {
        code: 0,
        message: "上传头像失败",
      };
    }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  //   console.log(url);
  res.send(result);
});

//9.查询某个用户数据
Router.get("/getuser/:id", async (req, res) => {
  let _id = ObjectId(req.params.id);
  // console.log(_id);
  let query = {
    _id,
  }; //{_id:ObjectId(5f51a143db619cff3c548934)}
  let result = {};
  try {
    let data = await mongo.find("users", { findquery: query }); //因为插入到数据库里面的数据必须是数组格式：arr是一个数组
    console.log(data);
    result = data;
    // if (data.code) {
    //   //登录成功
    //   //生成token
    //   result = {
    //     code: 1,
    //     message: "查询成功",
    //     data
    //   };
    // } else {
    //   result = {
    //     code: 0,
    //     message: "删除失败",
    //   };
    // }
  } catch (err) {
    result = {
      code: 0,
      message: "服务器异常",
    };
  }
  // res.send("登录成功");
  res.send(result); //响应数据给前端
  // res.send("2323");
});

module.exports = Router;
